package com.ruoyi.web.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.constant.WalletConstant;
import com.ruoyi.web.domain.RechargeRecord;
import com.ruoyi.web.domain.UserShareRecord;
import com.ruoyi.web.enums.CommonDictEnum;
import com.ruoyi.web.enums.RechargeRecordEnum;
import com.ruoyi.web.mapper.RechargeRecordMapper;
import com.ruoyi.web.mapper.UserCapitalMapper;
import com.ruoyi.web.mapper.UserShareRecordMapper;
import com.ruoyi.web.service.IUserShareRecordService;
import com.ruoyi.web.utils.CommonUtil;
import com.ruoyi.web.utils.IdWorker;
import com.ruoyi.web.utils.MysqlUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户分享记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-01-05
 */
@Service
@AllArgsConstructor
public class UserShareRecordServiceImpl implements IUserShareRecordService {
    private final UserShareRecordMapper userShareRecordMapper;
    private final IdWorker idWorker;
    private final RechargeRecordMapper rechargeRecordMapper;
    private final UserCapitalMapper capitalMapper;
    private final MysqlUtil mysqlUtil;
    private final ISysConfigService configService;
    private final CommonUtil commonUtil;

    @Override
    public R<String> upload(MultipartFile file) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new TadpoleException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
        }
        try {
            String upload = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);

            UserShareRecord param = new UserShareRecord();
            param.setUserId(userId);
            param.setFileUrl(upload);
            param.setIsReward(CommonDictEnum.YesOrNo.NO.getValue());
            commonUtil.initCreateAbout(param);
            // 用户分享记录
            if (userShareRecordMapper.add(param) != 1) {
                CommonUtil.throwError();
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new TadpoleException(AbnormalEnum.MSG.DISCONNECTED.getCode(), "Upload failed");
        }
    }


    @Override
    public R<String> saveReward(Long shareId) {
        try {
            BigDecimal num = new BigDecimal(configService.selectConfigByKey("USER_SHARE_REWARD"));
            UserShareRecord shareRecord = userShareRecordMapper.selectUserShareRecordById(shareId);
            if (shareRecord == null) {
                throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "未找到该分享记录");
            }
            if (shareRecord.getIsReward() != null && shareRecord.getIsReward().equals(CommonDictEnum.YesOrNo.YES.getValue())) {
                throw new TadpoleException(AbnormalEnum.MSG.UNSUPPORTED_OPERATION.getCode(), "该条分享记录已给用户发放过奖励");
            }
            mysqlUtil.startLocalTx();
            shareRecord.setIsReward(CommonDictEnum.YesOrNo.YES.getValue());
            userShareRecordMapper.updateUserShareRecord(shareRecord);
            // 修改资金
            capitalMapper.updateUserBalance(num, shareRecord.getUserId());
            // 充值记录
            RechargeRecord record = new RechargeRecord();
            record.setId(idWorker.nextId());
            record.setUserId(shareRecord.getUserId());
            record.setCurrency(WalletConstant.USDT);
            record.setType(RechargeRecordEnum.Type.SHARE_REWARD.getValue());
            record.setState(RechargeRecordEnum.Status.SUCCESS.getValue());
            record.setQuantity(num);
            rechargeRecordMapper.insertRechargeRecord(record);
            mysqlUtil.commitLocalTx();
            return R.ok();
        } catch (Exception e) {
            mysqlUtil.rollbackLocalTx();
            throw new TadpoleException(AbnormalEnum.MSG.DISCONNECTED.getCode(), "奖励失败");
        }
    }

    /**
     * 查询用户分享记录
     *
     * @param id 用户分享记录主键
     * @return 用户分享记录
     */
    @Override
    public UserShareRecord selectUserShareRecordById(Long id) {
        return userShareRecordMapper.selectUserShareRecordById(id);
    }

    /**
     * 查询用户分享记录列表
     *
     * @param userShareRecord 用户分享记录
     * @return 用户分享记录
     */
    @Override
    public List<UserShareRecord> selectUserShareRecordList(UserShareRecord userShareRecord) {
        return userShareRecordMapper.selectUserShareRecordList(userShareRecord);
    }

    /**
     * 新增用户分享记录
     *
     * @param userShareRecord 用户分享记录
     * @return 结果
     */
    @Override
    public int insertUserShareRecord(UserShareRecord userShareRecord) {
        userShareRecord.setCreateTime(DateUtils.getNowDate());
        return userShareRecordMapper.insertUserShareRecord(userShareRecord);
    }

    /**
     * 修改用户分享记录
     *
     * @param userShareRecord 用户分享记录
     * @return 结果
     */
    @Override
    public int updateUserShareRecord(UserShareRecord userShareRecord) {
        return userShareRecordMapper.updateUserShareRecord(userShareRecord);
    }

    /**
     * 批量删除用户分享记录
     *
     * @param ids 需要删除的用户分享记录主键
     * @return 结果
     */
    @Override
    public int deleteUserShareRecordByIds(Long[] ids) {
        return userShareRecordMapper.deleteUserShareRecordByIds(ids);
    }

    /**
     * 删除用户分享记录信息
     *
     * @param id 用户分享记录主键
     * @return 结果
     */
    @Override
    public int deleteUserShareRecordById(Long id) {
        return userShareRecordMapper.deleteUserShareRecordById(id);
    }
}
